<?php
namespace Controller;

class Domain extends Controller {
	private $MDomain = NULL;

	public function __construct() {
		$this->MDomain = new \Model\Domain();
	}

	public function index() {
		$this->display();
	}

	public function make() {
		$min = isset($_GET['min']) ? (int) $_GET['min'] : 0;
		$max = isset($_GET['max']) ? (int) $_GET['max'] : 0;
		$prefix = isset($_GET['prefix']) ? trim($_GET['prefix']) : '';
		$suffix = isset($_GET['suffix']) ? trim($_GET['suffix']) : '';
		
		$domain = array();
		
		for ($i = 0; $i < 50; $i++) {
			$domain[] = $prefix . $this->MDomain->make($min, $max) . $suffix;
		}
		
		$url = "/domain/make/min-$min/max-$max/prefix-$prefix/suffix-$suffix";
		
		$result = $this->MDomain->create($domain);
		if (strpos($result, 'you has been temporarily blocked from this tool')) {
			header("Location: /net/reconnect?src=" . urlencode($url));
		} else {
			header("Location: $url");
		}
	}

	public function sync() {
		$list = $this->MDomain->fetch();
		
		foreach ($list as $domain) {
			$result = $this->MDomain->sync(array($domain['name']));
			if (strpos($result, 'you has been temporarily blocked from this tool')) {
				header("Location: /net/reconnect?src=" . urlencode('/domain/sync'));
			} else {
				header('Location: /domain/sync');
			}
		}
	}

	public function fetch() {
		$well = isset($_GET['well']) ? (int) $_GET['well'] : 0;
		
		$list = $this->MDomain->fetch($well);
		
		$this->assign('list', $list);
		
		$this->display();
	}

	public function well() {
		$this->MDomain->well($_GET['domain']);
		
		header('Location: ' . $_SERVER['HTTP_REFERER']);
	}

	public function del() {
		if (isset($_GET['domain'])) {
			$this->MDomain->clean($_GET['domain']);
		} elseif (isset($_POST['domain'])) {
			foreach ($_POST['domain'] as $d) {
				$this->MDomain->clean($d);
			}
		}
		
		header('Location: ' . $_SERVER['HTTP_REFERER']);
	}

	public function clean() {
		$this->MDomain->clean();
		
		echo 'OK';
	}
}